# -*- coding: utf-8 -*-
import traceback

from flask import current_app as app
from flask import g, render_template, flash, session, redirect, url_for, request, abort
from flask.blueprints import Blueprint
from flask.helpers import jsonify
from sqlalchemy.sql.expression import and_, desc
from sqlalchemy.orm.exc import NoResultFound

from sys2do.views import BasicView, inventorynote
from sys2do.util.common import _g
from sys2do.constant import MESSAGE_INFO, TAB_HOME, PO_NEW, IVTNT_NEW, TNS_NEW, \
    ACTIVE, FIN_NEW, FIN_IN, FIN_OUT, MSG_NOT_ENOUGH_PARAMS, MESSAGE_ERROR, \
    MSG_NO_ID_SUPPLIED, MSG_SERVER_ERROR, SYSTEM_DATETIME_FORMAT, PO_APPROVE, \
    SO_APPROVE, MSG_NOT_ALL_PARAMS_OK
from sys2do.util.logic_helper import getPermission, getCurrentShopProfile
from sys2do.model import qry, Province, City, Supplier, PO, PODtl, Shop, Product, SysDict, SO, SODtl, DN, InventoryNote
from sys2do.util.decorator import myjson, templated

__all__ = ['bpAjax']

bpAjax = Blueprint( 'bpAjax', __name__ )

class AjaxView( BasicView ):

    template_folder = 'ajax'

    @myjson()
    def getShopList( self ):
        try:
            if getPermission( 'SHOP_VIEW_ALL' ):
                shops = [{'id' :s.id, 'name' : unicode( s )} for s in qry( Shop ).filter( and_( Shop.active == 0 ) )]
            else:
                shops = []
            return {'code' : 0 , 'data' : shops , 'msg' : 'OK'}
        except:
            self._error( traceback.format_exc() )
            return {'code' : 0 , 'data' : [], 'msg' : MSG_SERVER_ERROR}

    def supplier( self ):
        sid = _g( 'id' )
        try:
            if sid :
                obj = Supplier.get( sid )
                if not obj : raise NoResultFound
                data = obj.toJson()
            else:
                result = qry( Supplier ).filter( and_( Supplier.active == 0 ) ).order_by( Supplier.name )
                data = [obj.toJson() for obj in result]
        except:
            return jsonify( {'code' : 1, 'msg' : MSG_SERVER_ERROR} )
        return jsonify( {'code' : 0, 'data' : data} )



    def province( self ):
        cs = qry( City ).filter( and_( City.active == 0, City.parent_code == Province.code, Province.id == _g( 'pid' ) ) ).order_by( City.name )
        data = [{'id' : c.id, 'name' : c.name } for c in cs]
        return jsonify( {'code' : 0 , 'msg' : '' , 'data' : data} )


    @myjson()
    def searchPOPrice( self ):
        no = _g( 'q' )
        if not no : return {'code' : 1, 'msg' : MSG_NOT_ENOUGH_PARAMS}
        try:
            cs = [
                  PO.active == ACTIVE, PO.id == PODtl.hdrID, PODtl.pdtID == Product.id,
                  Product.no == no, PO.status == PO_APPROVE,
                  ]

            result = qry( Product, PO, PODtl ).filter( and_( *cs ) ).order_by( desc( PO.sysCreateTime ) )

            return {
                    'code' : 0 , 'msg' : 'OK',
                    'data' : [{
                               'pid' : pdt.id,
                               'time' : dtl.sysCreateTime.strftime( SYSTEM_DATETIME_FORMAT ),
                               'orderno' : hdr.no, 'product_no' : pdt.no ,
                               'product_name' : pdt.name, 'price' : unicode( dtl.realPrice ),
                               'creator' : unicode( hdr.createBy ),
                               } for ( pdt, hdr, dtl ) in result[:3]]
                    }
        except:
            self._error( traceback.format_exc() )
            return {'code' : 1 , 'msg' : MSG_SERVER_ERROR, 'data' : []}

    @templated( 'popup_recent_price.html' )
    def popupRecentPrice( self ):
        no = _g( 'q' )
        name = _g( 'name' )
        if not no or not name: return {'code' : 1, 'msg' : MSG_NOT_ENOUGH_PARAMS}
        try:
            result = []
            label = None
            if name == 'SO':
                label = u'销售'
                cs = [SO.active == ACTIVE, SO.id == SODtl.hdrID, SODtl.pdtID == Product.id,
                    Product.no == no, SO.status == SO_APPROVE, ]
                result = qry( Product, SO, SODtl ).filter( and_( *cs ) ).order_by( desc( SO.sysCreateTime ) )
            return {
                    'code' : 0 , 'msg' : 'OK', 'label': label,
                    'data' : [{
                               'pid' : pdt.id,
                               'time' : dtl.sysCreateTime.strftime( SYSTEM_DATETIME_FORMAT ),
                               'orderno' : hdr.no, 'product_no' : pdt.no ,
                               'product_name' : pdt.name, 'price' : unicode( dtl.realPrice ),
                               'creator' : unicode( hdr.createBy ),
                               } for ( pdt, hdr, dtl ) in result[:3]]
                    }
        except:
            self._error( traceback.format_exc() )
            return {'code' : 1 , 'msg' : MSG_SERVER_ERROR, 'data' : []}

    @templated( 'popup_product.html' )
    def popupProduct( self ):
        return {'obj': Product.get( _g( 'id' ) )}

    def popupGoto( self ):
        q = _g( 'q' )
        if not q or not q.isdigit():
            return {'code': 1, 'msg': MSG_NOT_ALL_PARAMS_OK}

        try:
            pre = qry( SysDict ).filter( and_( SysDict.type == 'OBJECT_PREFIX', SysDict.value == q[:3] ) ).one()
            import sys2do.model as model
            clz = getattr( model, pre.name )
            obj = qry( clz ).filter( clz.no == q ).one()
            template_name = None
            if clz == SO:
                template_name = 'popup_goto_so.html'
            elif clz == PO:
                template_name = 'popup_goto_po.html'
            elif clz == DN:
                template_name = 'popup_goto_dn.html'
            elif clz == Product:
                template_name = 'popup_goto_pdt.html'
            elif clz == InventoryNote:
                template_name = 'popup_goto_ivtnt.html'
            else:
                return {'code': 1, 'msg': MSG_NOT_ALL_PARAMS_OK}
            return render_template( '%s/%s' % ( self.template_folder.replace( '.', '/' ), template_name ), obj = obj )
        except:
            self._error( traceback.format_exc() )
            return {'code': 1, 'msg': MSG_SERVER_ERROR}


bpAjax.add_url_rule( '/', view_func = AjaxView.as_view( 'view' ), defaults = {'action':'index'} )
bpAjax.add_url_rule( '/<action>', view_func = AjaxView.as_view( 'view' ) )
